#include "chat_client.h"
#include <QDebug>
#include <QFileDialog>
chat_client::chat_client(QObject *parent) : QObject(parent)
{
    client = new QTcpSocket(this);
    connect(client, &QIODevice::readyRead, this, &chat_client::readyReadSlot);
    connect(client, &QTcpSocket::connected, this, &chat_client::onconnectd);
    connect(client, &QTcpSocket::disconnected, this, &chat_client::disconnectd);
}

chat_client *chat_client::getInstance()
{
    static chat_client chat;
    return &chat;
}

chat_client::~chat_client()
{
}

void chat_client::requestFileList()
{
    QTextStream output(client);
    output << "REQUEST_FILE_LIST\n";
}

void chat_client::downloadFile(const QString &filename)
{
    QTextStream output(client);
    output << "GETFILE" << filename;
}

void chat_client::connetToserver(const QString &ip, const int &port)
{
    qDebug() << "connectToserver ip:" + ip + "port:" + port;
    client->connectToHost(ip, port);
}

void chat_client::sendToserver(const QString &id, const QString &msg)
{
    //拼接处理
    QString text = "INFO" + id + ":" + msg;
    //创建文本流对象
    QTextStream output(client);
    //输出给服务端
    output << text;
}

QString chat_client::readForserver(const QString &msg)
{
    return msg;
}

void chat_client::readyReadSlot()
{
    QTextStream input(client);
    QString text = input.readAll();
    if (text.startsWith("INFO"))
        emit newMsg_sig(text.mid(4));

    else if (text.startsWith("FILE_LIST")) {
        //处理text,按行排列
        QStringList files = text.mid(10).split("\n", QString::SkipEmptyParts);
        emit fileListReceived(files);
    }
    else if (text.startsWith("FILEDATA")) {
        QStringList parts = text.split("\n", QString::SkipEmptyParts);
        if (parts.size() >= 3) {
            QString filename = parts[1];
            QByteArray fileData = QByteArray::fromBase64(parts[2].toUtf8());

            QString savePath =
                QFileDialog::getSaveFileName(nullptr, "保存文件", filename);
            if (!savePath.isEmpty()) {
                QFile file(savePath);
                if (file.open(QIODevice::WriteOnly)) {
                    file.write(fileData);
                    file.close();
                    emit fileDownloaded(filename, savePath);
                }
            }
        }
    }
}
void chat_client::onconnectd()
{
    qDebug() << "conneted to server";
    emit onconnectd_sig();
}

void chat_client::disconnectd()
{
    qDebug() << "disconnected from server";
    emit disconnectd_sig();
}
